<?php
class IndexController extends zShang_Controller_Action {


    public function indexAction() {        
        $auth = Zend_Auth::getInstance();
        $infoUser = $auth->getIdentity();
        //$this->view->fullName = $infoUser->username;
        $this->view->fullname = 'default:index';
    }

    /**
     * Ref: http://www.zend.vn/public/lap-trinh/zend-framework/zend-auth-voi-vi-du-login-logout/l1l6l59.html
     */
    public function loginAction() {
        echo 'default:login';
        if ($this->_request->isPost()) {
            // Connect DB
            $db = Zend_Registry::get('connectDB');
            // Start Zend Auth
            $auth = Zend_Auth::getInstance();
            $authAdapter = new Zend_Auth_Adapter_DbTable($db);
            $authAdapter->setTableName('users')
                        ->setIdentityColumn('username')
                        ->setCredentialColumn('password');

            // Get data from form
            $uname = $this->_request->getParam('username');
            $paswd = $this->_request->getParam('password');

            // Auth
            $authAdapter->setIdentity($uname);
            $authAdapter->setCredential(md5($paswd));

            // Check role
            $select = $authAdapter->getDbSelect();

            $result = $auth->authenticate($authAdapter);
            $flag = false;
            if ($result->isValid()) {
                $data = $authAdapter->getResultRowObject(null, array('password'));
                $auth->getStorage()->write($data);
                $flag = true;
            }
            
            $registry = Zend_Registry::getInstance();
            $session = $registry->get('session');
            
            if ($flag == true) {
                $this->_redirect('/index/index');
            }
            
            
        }
    }

    public function logoutAction() {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
    }
}
